// WebSocketManager.ts
import { _decorator, EventTarget } from 'cc';
import EventDefine from '../config/EventDefine';
import { GameController } from './GameController';
import { ConfigModule } from '../config/ConfigModule';
import { URLParams } from '../utils/URLParams';

export default class WebSocketManager {
    private static instance: WebSocketManager;
    private ws: WebSocket | null = null;
    private eventTarget = GameController.Instance.eventTarget;
    private reconnectAttempts: number = 0;
    private maxReconnectAttempts: number = 3;
    private reconnectInterval: number = 3000; // 重连间隔(ms)
    private heartbeatInterval: number = 30000; // 心跳间隔(ms)
    private heartbeatTimer: any = null;
    private currentUrl: string = ''; // 保存当前连接的URL

    private constructor() { }

    public static getInstance(): WebSocketManager {
        if (!WebSocketManager.instance) {
            WebSocketManager.instance = new WebSocketManager();
        }
        return WebSocketManager.instance;
    }

    public socketIsOpen(): boolean {
        if (this.ws != null && this.ws.readyState === WebSocket.OPEN) {
            return true;
        }
        return false
    }

    // 连接服务器
    public connect(): void {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) return;

        // 根据URL参数判断使用哪个连接地址
        const isTest = URLParams.getParam('test');
        const url = isTest ? ConfigModule.WS_TEST_URL : ConfigModule.WS_URL;
        this.currentUrl = url;

        this.ws = new WebSocket(url);

        this.ws.onopen = () => {
            console.log('WebSocket connected to:', url);
            this.reconnectAttempts = 0;
            setTimeout(() => {
                this.startHeartbeat();
            }, 3000);
            this.eventTarget.emit(EventDefine.wsOpen)
        };

        this.ws.onmessage = (event: MessageEvent) => {
            try {
                const data = JSON.parse(event.data);
                GameController.Instance.onmessageHandle(data);
            } catch (error) {
                console.error('Message parse error:', error);
            }
        };

        this.ws.onerror = (error) => {
            console.error('WebSocket error:', error);
            this.eventTarget.emit(EventDefine.wsError, error)
        };

        this.ws.onclose = (event) => {
            console.log('WebSocket closed:', event.reason);
            this.stopHeartbeat();
            if (event.code !== 1000) { // 非正常关闭时重连
                this.handleReconnect();
            }
            this.eventTarget.emit(EventDefine.wsClose, event)
        };
    }

    // 发送消息
    public send(data: any): void {
        console.log("[WS Send Data]", data)
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            const message = JSON.stringify(data);
            this.ws.send(message);
        } else {
            console.error('WebSocket not connected');
        }
    }

    // 关闭连接
    public close(): void {
        if (this.ws) {
            this.ws.close(1000, 'Manual close');
            this.ws = null;
        }
    }

    // 心跳检测
    private startHeartbeat(): void {
        this.heartbeatTimer = setInterval(() => {
            const sendData = {
                action: "1",
                token: GameController.Instance.token
            }
            this.send(sendData);
        }, this.heartbeatInterval);
    }

    private stopHeartbeat(): void {
        if (this.heartbeatTimer) {
            clearInterval(this.heartbeatTimer);
            this.heartbeatTimer = null;
        }
    }

    // 自动重连
    private handleReconnect(): void {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            setTimeout(() => {
                console.log(`Reconnecting (attempt ${this.reconnectAttempts})...`);
                this.connect();
            }, this.reconnectInterval);
        } else {
            console.error('Max reconnect attempts reached');
        }
    }
}